<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/24 13:59:44 $)
// $RCSfile: functions_staff.php,v $ : $Revision: 1.22 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}


/**
* ###############################################
* CLASS DECLARATION
* ###############################################
*/


/**
* Class to handle all staff related actions
*/
class Staff
{
	/**
	* Inserts a new Staff Group
	*/
	function insertGroup($title, $isadmin = false, $permarray)
	{
		global $_SWIFT, $dbCore;
		
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."staffgroup` (`title`, `isadmin`) VALUES('". $dbCore->escape($title) ."', '". iif($isadmin==true, "1", "0") ."');");
		$staffgroupid = $dbCore->lastInsertId();

		foreach ($permarray as $permkey=>$permval)
		{
			$permquery .= "('". intval($staffgroupid) ."', '". $dbCore->escape($permkey) ."', '". $dbCore->escape($permval) ."'),";
		}

		if (trim($permquery) != "")
		{
			$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."staffgroupsettings` (`staffgroupid`, `name`, `value`) VALUES ". preg_replace("/,$/", "", $permquery) .";");			
		}

		rebuildStaffCache();
		rebuildStaffGroupCache();
		rebuildGroupSettingsCache();

		return $staffgroupid;
	}

	/**
	* Inserts a new staff member
	*/
	function insertStaff($fullname, $username, $password, $staffgroupid, $email, $mobilenumber, $signature, $groupassigns = true)
	{
		global $_SWIFT, $dbCore;

		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."staff` (`fullname`, `username`, `password`, `staffgroupid`, `email`, `mobilenumber`, `lastvisit`, `lastactivity`, `timezoneoffset`, `enabledst`, `startofweek`, `pmunread`, `groupassigns`, `enablepmalerts`, `enablepmjsalerts`) VALUES ('". $dbCore->escape($fullname) ."', '". $dbCore->escape($username) ."', '". md5($password) ."', '". $dbCore->escape($staffgroupid) ."', '". $dbCore->escape($email) ."', '". $dbCore->escape($mobilenumber) ."', '". DATENOW ."', '". DATENOW ."', '99', '0', '', '0', '". iif($groupassigns, "1", "0") ."', '1', '1');");
		$staffid = $dbCore->lastInsertId();
		if (empty($staffid))
		{
//			echo "Failed to Insert Staff: ". $dbCore->fetchLastError();
//			exit;
			return false;
		}

		// Add the staff signature
		$dbCore->query("INSERT INTO `". TABLE_PREFIX ."signatures` (`dateline`, `staffid`, `signature`) VALUES ('". DATENOW ."', '". intval($staffid) ."', '". $dbCore->escape($signature) ."');");

		$dbCore->query("INSERT INTO `".TABLE_PREFIX ."staffschedules` (`staffid`, `sunday_enabled`, `sunday_open`, `sunday_close`, `monday_enabled`, `monday_open`, `monday_close`, `tuesday_enabled`, `tuesday_open`, `tuesday_close`, `wednesday_enabled`, `wednesday_open`, `wednesday_close`, `thursday_enabled`, `thursday_open`, `thursday_close`, `friday_enabled`, `friday_open`, `friday_close`, `saturday_enabled`, `saturday_open`, `saturday_close`) VALUES ('". intval($staffid) ."', '0', '00:00', '23:45', '1', '08:00', '19:00', '1', '08:00', '19:00', '1', '08:00', '19:00', '1', '08:00', '19:00', '1', '08:00', '19:00', '0', '00:00', '23:45');");

		return $staffid;
	}

	/**
	* Assigns a staff to the given departments
	*/
	function assignStaff($staffid, $departmentidarray)
	{
		global $dbCore, $_SWIFT;

		if (!is_array($departmentidarray))
		{
			return false;
		}

		if (count($departmentidarray) == 0)
		{
			return false;
		}
		
		if (!$staffid)
		{
			return false;
		}

		for ($ii=0; $ii<count($departmentidarray); $ii++)
		{
			$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."staffassigns` (`departmentid`, `staffid`) VALUES('". $dbCore->escape($departmentidarray[$ii]) ."', '". intval($staffid) ."');");
		}

		rebuildStaffAssignCache();
		
		return true;
	}

	/**
	* Deletes a staff with given staff id
	*/
	function deleteStaff($staffidarray)
	{
		global $_SWIFT, $dbCore, $module;

		$_alertid = array();

		if (!is_array($staffidarray))
		{
			return false;
		}
	
		// MAHESH: This resets the assigned status of tickets that were earlier assigned to this staff.
		if($module->isRegistered(MODULE_TICKETS))
		{
			$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `ownerstaffid` = '0' WHERE `ownerstaffid` IN (". buildIN($staffidarray) .");");
		}

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staff` WHERE `staffid` IN (". buildIN($staffidarray) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staffassigns` WHERE `staffid` IN (". buildIN($staffidarray) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."signatures` WHERE `staffid` IN (". buildIN($staffidarray) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staffschedules` WHERE `staffid` IN (". buildIN($staffidarray) .");");
		
		// Mahesh: Delete Private Staff alerts
		$dbCore->query("SELECT `alertruleid` FROM `". TABLE_PREFIX ."alertrules` WHERE `staffid` IN (". buildIN($staffidarray) .") AND `alertscope` = '0';");
		while ($dbCore->nextRecord())
		{
			$_alertid[] = $dbCore->Record["alertruleid"];
		}
		
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."alertrules` WHERE `alertruleid` IN (". buildIN($_alertid) .");");
		
		require_once("./modules/tickets/functions_alertrulesui.php");
		deleteAllAlertActions($_alertid);
		
		rebuildStaffCache();

		return true;
	}

	/**
	* Deletes the given staff groups with the provided ids
	*/
	function deleteStaffGroups($staffgroupidarray)
	{
		global $_SWIFT, $dbCore;

		if (!is_array($staffgroupidarray))
		{
			return false;
		}

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staffgroup` WHERE `staffgroupid` IN (". buildIN($staffgroupidarray) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staff` WHERE `staffgroupid` IN (". buildIN($staffgroupidarray) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staffgroupsettings` WHERE `staffgroupid` IN (". buildIN($staffgroupidarray) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."groupassigns` WHERE `staffgroupid` IN (". buildIN($staffgroupidarray) .");");

		rebuildStaffGroupCache();
		rebuildStaffCache();
		rebuildGroupSettingsCache();

		return true;
	}
}

/**
* Updates the current staff ticketviewid
*/
function updateStaffTicketView($ticketviewid)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."staff` SET `ticketviewid` = '". intval($ticketviewid) ."' WHERE `staffid` = '". intval($_SWIFT["staff"]["staffid"]) ."';");
	$_SWIFT["staff"]["ticketviewid"] = intval($ticketviewid);

	rebuildStaffCache();
}

/**
* Clear the group assignments
*/
function clearGroupAssigns($staffgroupid)
{
	global $dbCore;

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."groupassigns` WHERE `staffgroupid` = '". intval($staffgroupid) ."';");

	rebuildGroupAssignCache();

	return true;
}

/**
* Assigns a staff group to the given departments
*/
function assignGroup($staffgroupid, $departmentidarray)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($departmentidarray))
	{
		return false;
	}
	
	if (!$staffgroupid)
	{
		return false;
	}

	for ($ii=0; $ii<count($departmentidarray); $ii++)
	{
		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."groupassigns` (`departmentid`, `staffgroupid`) VALUES('". $dbCore->escape($departmentidarray[$ii]) ."', '". intval($staffgroupid) ."');");
	}

	rebuildGroupAssignCache();
	
	return true;
}

/**
* Clear staff assigns
*/
function clearStaffAssigns($staffid)
{
	global $dbCore, $_SWIFT;

	if (!$staffid)
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staffassigns` WHERE `staffid` = '". intval($staffid) ."';");

	return true;
}

/**
* Edit an existing staff member details through preferences
*/
function updateStaffPreferences($staffid, $fullname, $password, $email, $mobilenumber, $signature, $timezoneoffset, $enablepmalerts, $enablepmjsalerts, $enabledst = false)
{
	global $_SWIFT, $dbCore;

	if (empty($password))
	{
		$pwupdate = false;
	} else {
		// Set new pw
		$pwupdate = true;
	}
	
	$dbCore->query("UPDATE `". TABLE_PREFIX ."staff` SET `fullname` = '". $dbCore->escape($fullname) ."'". iif($pwupdate==true, ", `password` = '". md5($password) ."'") .", `email` = '". $dbCore->escape($email) ."', `mobilenumber` = '". $dbCore->escape($mobilenumber) ."', `timezoneoffset` = '". $dbCore->escape($timezoneoffset) ."', `enabledst` = '". iif($enabledst==true, "1", "0") ."', `enablepmalerts` = '". iif($enablepmalerts==true, "1", "0") ."', `enablepmjsalerts` = '". iif($enablepmjsalerts==true, "1", "0") ."' WHERE staffid = '". intval($staffid) ."';");

	// Update the staff signature
	$dbCore->query("UPDATE `". TABLE_PREFIX ."signatures` SET `signature` = '". $dbCore->escape($signature) ."' WHERE `staffid` = '". intval($staffid) ."';");

	rebuildStaffCache();

	return true;
}


/**
* Change Staff Password
*/
function changeStaffPassword($staffid, $password)
{
	global $_SWIFT, $dbCore;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."staff` SET `password` = '". md5($password) ."' WHERE staffid = '". intval($staffid) ."';");

	return true;
}

/**
* Edit an existing staff member
*/
function updateStaff($staffid, $fullname, $username, $password, $staffgroupid, $email, $mobilenumber, $signature, $groupassigns = true)
{
	global $_SWIFT, $dbCore;

	if (empty($password))
	{
		$pwupdate = false;
	} else {
		// Set new pw
		$pwupdate = true;
	}
	
	$dbCore->query("UPDATE `". TABLE_PREFIX ."staff` SET `fullname` = '". $dbCore->escape($fullname) ."', `username` = '". $dbCore->escape($username) ."'". iif($pwupdate==true, ", `password` = '". md5($password) ."'") .", `staffgroupid` = '". intval($staffgroupid) ."', `email` = '". $dbCore->escape($email) ."', `mobilenumber` = '". $dbCore->escape($mobilenumber) ."', `groupassigns` = '". iif($groupassigns, "1", "0") ."' WHERE `staffid` = '". intval($staffid) ."';");

	// Update the staff signature
	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."signatures` SET `signature` = '". $dbCore->escape($signature) ."' WHERE `staffid` = '". intval($staffid) ."';");

	rebuildStaffCache();

	return true;
}

/**
* Rebuilds the staff cache
*/
function rebuildStaffCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$staffarray = array();

	$dbCore->query("SELECT staff.*, staffgroup.*, signatures.*, staff.staffid AS sstaffid FROM `". TABLE_PREFIX ."staff` AS staff LEFT JOIN `". TABLE_PREFIX ."signatures` AS signatures ON (staff.staffid = signatures.staffid) LEFT JOIN `". TABLE_PREFIX ."staffgroup` AS staffgroup ON(staff.staffgroupid = staffgroup.staffgroupid) ORDER BY staff.fullname ASC;");
	while ($dbCore->nextRecord())
	{
		$staffarray[$dbCore->Record["sstaffid"]]["staffid"] = $dbCore->Record["sstaffid"];
		$staffarray[$dbCore->Record["sstaffid"]]["staffgroupid"] = $dbCore->Record["staffgroupid"];
		$staffarray[$dbCore->Record["sstaffid"]]["fullname"] = $dbCore->Record["fullname"];
		$staffarray[$dbCore->Record["sstaffid"]]["username"] = $dbCore->Record["username"];
		$staffarray[$dbCore->Record["sstaffid"]]["email"] = $dbCore->Record["email"];
		$staffarray[$dbCore->Record["sstaffid"]]["groupassigns"] = $dbCore->Record["groupassigns"];
		$staffarray[$dbCore->Record["sstaffid"]]["ticketviewid"] = $dbCore->Record["ticketviewid"];
		if (!empty($dbCore->Record["mobilenumber"]))
		{
			$staffarray[$dbCore->Record["sstaffid"]]["mobilenumber"] = $dbCore->Record["mobilenumber"];
		}
	}

	$datastore->update("staffcache", $staffarray);
}

/**
* Rebuilds the staff group cache
*/
function rebuildStaffGroupCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$groupcache = array();
	$groupsettings = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."staffgroupsettings` ORDER BY `sgroupsettingid` ASC;");
	while ($dbCore->nextRecord())
	{
		$groupsettings[$dbCore->Record["staffgroupid"]][$dbCore->Record["name"]] = $dbCore->Record["value"];
	}

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."staffgroup` ORDER BY `staffgroupid` ASC;");
	while ($dbCore->nextRecord())
	{
		$groupcache[$dbCore->Record["staffgroupid"]] = $dbCore->Record;
		$groupcache[$dbCore->Record["staffgroupid"]]["settings"] = $groupsettings[$dbCore->Record["staffgroupid"]];
	}

	$datastore->update("staffgroupcache", $groupcache);
}

/**
* Rebuilds the Staff Department Assignment Cache
*/
function rebuildStaffAssignCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$staffassign = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."staffassigns` ORDER BY `staffassignid` ASC;");
	while ($dbCore->nextRecord())
	{
		$staffassign[$dbCore->Record["staffid"]][] = $dbCore->Record["departmentid"];	
	}

	$datastore->update("staffassigncache", $staffassign);
}

/**
* Rebuilds the Group Assignment Cache
*/
function rebuildGroupAssignCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$groupassign = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."groupassigns` ORDER BY `groupassignid` ASC;", 3);
	while ($dbCore->nextRecord(3))
	{
		$groupassign[$dbCore->Record3["staffgroupid"]][] = $dbCore->Record3["departmentid"];
	}

	$datastore->update("groupassigncache", $groupassign);
}

/**
* Rebuilds the Staff Group Permission Cache
*/
function rebuildGroupSettingsCache()
{
	global $_SWIFT, $dbCore, $datastore;

	$groupsettings = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."staffgroupsettings` ORDER BY `sgroupsettingid` ASC;");
	while ($dbCore->nextRecord())
	{
		$groupsettings[$dbCore->Record["staffgroupid"]][$dbCore->Record["name"]] = $dbCore->Record["value"];
	}

	$datastore->update("groupsettingcache", $groupsettings);
}

/**
* Displays the form for EDIT and INSERT
*/
function displayStaffForm($type)
{
	global $dbCore, $_SWIFT;

	printFormStart("staffform");
	printMainTableHeader(iif($type==INSERT,$_SWIFT["language"]["staffdetails"], $_SWIFT["language"]["editstaff"]));

	// ======= REQUIRED FIELDS =======
	printDescRow($_SWIFT["language"]["staffdetails"]);
	printTextRow("fullname", $_SWIFT["language"]["stafffullname"], $_SWIFT["language"]["desc_stafffullname"], "text", $_POST["fullname"]);
	printTextRow("username", $_SWIFT["language"]["staffusername"], $_SWIFT["language"]["desc_staffusername"], "text", $_POST["username"], "20");
	printTextRow("password", $_SWIFT["language"]["staffpassword"], iif($type==INSERT, $_SWIFT["language"]["desc_staffpassword"], $_SWIFT["language"]["desc_staffpasswordedit"]), "password", $_POST["password"], "20");
	printTextRow("passwordconfirm", $_SWIFT["language"]["staffpasswordconfirm"], $_SWIFT["language"]["desc_staffpasswordconfirm"], "password", $_POST["passwordconfirm"], "20");
	printTextRow("email", $_SWIFT["language"]["staffemail"], $_SWIFT["language"]["desc_staffemail"], "text", $_POST["email"]);
	$cnt = 0;
	foreach ($_SWIFT["staffgroupcache"] as $key=>$val)
	{
		$options[$cnt]["title"] = $val["title"];
		$options[$cnt]["value"] = $key;
		$options[$cnt]["selected"] = iif($cnt==0, true, false);
		$cnt++;
	}

	printSelectRow("staffgroupid", $_SWIFT["language"]["staffgroup"], $_SWIFT["language"]["desc_staffgroup"], $options);

	// ======= OPTIONAL FIELDS =======
	printDescRow($_SWIFT["language"]["optionalfields"]);
	printTextRow("mobilenumber", $_SWIFT["language"]["staffmobilenumber"], $_SWIFT["language"]["desc_staffmobilenumber"], "text", $_POST["mobilenumber"], "20");

	if ($type == EDIT)
	{
		$_signature = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."signatures` WHERE `staffid` = '". intval($_POST["staffid"]) ."';");
		$_POST["signature"] = $_signature["signature"];
	}
	printTextareaRow("signature", $_SWIFT["language"]["staffsignature"], $_SWIFT["language"]["desc_staffsignature"], $_POST["signature"], 60, 4);

	// ======= ASSIGNED DEPARTMENTS =======
	printDescRow($_SWIFT["language"]["staffassigneddep"]);
	printYesNoRow("usegroupdep", $_SWIFT["language"]["usegroupdep"], $_SWIFT["language"]["desc_usegroupdep"], iif($_POST["groupassigns"]==1, true, false), "statusDepartmentSelect();");
	$cnt = 0;
	$options = array();

	foreach ($_SWIFT["departmentcache"] as $key=>$val)
	{
		$modtitle = "module_". $val["departmentmodule"];
		$options[$cnt]["title"] = sprintf($_SWIFT["language"]["twodesc"], $val["title"], $_SWIFT["language"][$modtitle]);;
		$options[$cnt]["value"] = $key;
		if ($type == EDIT)
		{
			if (in_array($val["departmentid"], $_SWIFT["staffassigncache"][$_POST["staffid"]]))
			{
				$options[$cnt]["selected"] = true;				
			} else {
				$options[$cnt]["selected"] = false;				
			}
		} else {
			// All departments are checked if its the insert area
			$options[$cnt]["selected"] = true;
		}
		$cnt++;
	}
	printSelectMultipleRow("assigneddepid", $_SWIFT["language"]["assigneddep"], $_SWIFT["language"]["desc_assigneddep"], $options);

	
	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertstaff"], $_SWIFT["language"]["updatestaff"]));

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", iif($type==INSERT, "insertstaff", "editstaff"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("staffid", $_POST["staffid"]);
	}
	printFormEnd();
	?>
	<script language="Javascript">
		statusDepartmentSelect();

		function statusDepartmentSelect()
		{
			if (document.staffform.usegroupdep[0].checked)
			{
				disableField(document.staffform.elements['assigneddepid[]']);
			} else {
				enableField(document.staffform.elements['assigneddepid[]']);
			}
		}
	</script>
	<?
}

/**
* Renders the EDIT/INSERT Staff Group Form
*/
function renderStaffGroupForm($type)
{
	global $dbCore, $_SWIFT, $permissions, $module;

	printFormStart("staffgroupform");
	printMainTableHeader($_SWIFT["language"]["staffgroupdetails"]);

	printDescRow($_SWIFT["language"]["generalfields"]);

	printTextRow("title", $_SWIFT["language"]["grouptitle"], $_SWIFT["language"]["desc_grouptitle"], "text", $_POST["title"]);
	printYesNoRow("isadmin", $_SWIFT["language"]["groupisadmin"], $_SWIFT["language"]["desc_groupisadmin"], iif($_POST["isadmin"]==1, true, false));

	$cnt = 0;
	$options = array();
	foreach ($_SWIFT["departmentcache"] as $key=>$val)
	{
		$modtitle = "module_". $val["departmentmodule"];
		$options[$cnt]["title"] = sprintf($_SWIFT["language"]["twodesc"], $val["title"], $_SWIFT["language"][$modtitle]);;
		$options[$cnt]["value"] = $key;
		if ($type == EDIT)
		{
			if (in_array($val["departmentid"], $_SWIFT["groupassigncache"][$_POST["staffgroupid"]]))
			{
				$options[$cnt]["selected"] = true;				
			} else {
				$options[$cnt]["selected"] = false;				
			}
		} else {
			// Always enabled for insert
			$options[$cnt]["selected"] = true;
		}
		$cnt++;
	}
	printSelectMultipleRow("assigneddepid", $_SWIFT["language"]["groupassigneddep"], $_SWIFT["language"]["desc_groupassigneddep"], $options);

	require_once ("./modules/core/config_permissions.php");
	foreach ($_perm as $key=>$val)
	{
		if ($module->isRegistered($key))
		{
			printDescRow($_SWIFT["language"]["mod_".$key]);

			foreach ($val as $permkey=>$perm)
			{
				if ($permissions[$perm] == "1")
				{
					$permres = true;
				} else if ($permissions[$perm] == "") {
					$permres = true;
				} else {
					$permres = false;
				}

				printYesNoRow("perm[". $perm ."]", $_SWIFT["language"][$perm], "", $permres);
			}
		}
	}
	
	printSubmitRow(iif($type==INSERT,$_SWIFT["language"]["insertstaffgroup"],$_SWIFT["language"]["update"]));

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", iif($type==INSERT, "insertstaffgroup", "editstaffgroup"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("staffgroupid", $_POST["staffgroupid"]);		
	}
	printFormEnd();
}

/**
* Update an existing Staff Group
*/
function updateStaffGroup($staffgroupid, $title, $isadmin = false, $permarray)
{
	global $_SWIFT, $dbCore;
	
	$dbCore->query("UPDATE `". TABLE_PREFIX ."staffgroup` SET `title` = '". $dbCore->escape($title) ."', `isadmin` = '". iif($isadmin==true, "1", "0") ."' WHERE `staffgroupid` = '". intval($staffgroupid) ."';");

	foreach ($permarray as $permkey=>$permval)
	{
		$permquery .= "('". intval($staffgroupid) ."', '". $dbCore->escape($permkey) ."', '". $dbCore->escape($permval) ."'),";
	}

	if (trim($permquery) != "")
	{
		$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."staffgroupsettings` (`staffgroupid`, `name`, `value`) VALUES ". preg_replace("/,$/", "", $permquery) .";");			
	}

	rebuildStaffGroupCache();
	rebuildGroupSettingsCache();
	rebuildStaffCache();

	return true;
}

/**
* Sends a mass mail to all staff under the specified groups
*/
function sendMassMail($staffgroupidlist, $subject, $contents)
{
	global $dbCore, $_SWIFT, $template;

	if (!_is_array($staffgroupidlist))
	{
		return false;
	}

	require_once ("./includes/functions_mail.php");
	$mailObj = new SWIFT_Mail();

	// Set to master group
	$template->setGroup(1);

	$template->assign("contentshtml", getProcessedHTML($contents));
	$template->assign("contentstext", getProcessedText($contents));

	$template->assign("ishtml", false);
	$emailtext = $template->displayTemplate("staffmassmail", TEMPLATE_DB);
	$template->assign("ishtml", true);
	$emailhtml = $template->displayTemplate("staffmassmail", TEMPLATE_DB);
		
	$mailObj->setSubject($subject);
	$mailObj->setData($emailhtml, $emailtext);

	$mailcount = 0;
	$dbCore->query("SELECT `email` FROM `". TABLE_PREFIX ."staff` WHERE `staffgroupid` IN (". buildIN($staffgroupidlist) .");");
	$emaillist = array();
	while ($dbCore->nextRecord())
	{
		$emaillist[] = $dbCore->Record["email"];
		$mailcount++;
	}

	$mailObj->sendMail($emaillist, $_SWIFT["staff"]["email"], $_SWIFT["staff"]["fullname"], true);

	return $mailcount;
}

/**
* Rebuild staff group permissions.. Used during setup and upgrade
*/
function rebuildStaffGroupPermissions()
{
	global $dbCore;

	// Get all registered modules
	$modulelist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."settings` WHERE `section` = 'registeredmodules';");
	while ($dbCore->nextRecord())
	{
		$modulelist[] = $dbCore->Record["vkey"];
	}
	$modulelist[] = MODULE_CORE;

	// Get all Staff Group IDs
	$staffgroupidlist = array();
	$dbCore->query("SELECT `staffgroupid` FROM `". TABLE_PREFIX ."staffgroup` ORDER BY `staffgroupid` ASC;");
	while ($dbCore->nextRecord())
	{
		$staffgroupidlist[] = $dbCore->Record["staffgroupid"];
	}

	$_settingcache = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."staffgroupsettings`;");
	while ($dbCore->nextRecord())
	{
		$_settingcache[$dbCore->Record["staffgroupid"]][$dbCore->Record["name"]] = $dbCore->Record["value"];
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."staffgroupsettings`;");

	// Rebuild all Staff permissions
	require_once ("./modules/core/config_permissions.php");
	$permsql = array();
	foreach ($_perm as $key=>$val)
	{
		if (in_array($key, $modulelist))
		{
			foreach ($val as $permkey=>$permval)
			{
				for ($ii=0; $ii<count($staffgroupidlist); $ii++)
				{
					if (isset($_settingcache[$staffgroupidlist[$ii]][$permval]))
					{
						$_setvalue = $_settingcache[$staffgroupidlist[$ii]][$permval];
					} else {
						$_setvalue = 1;
					}
					$permsql[] = "('". intval($staffgroupidlist[$ii]) ."', '". $permval ."', '". $_setvalue ."')";
				}
			}
		}
	}

	$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."staffgroupsettings` (`staffgroupid`, `name`, `value`) VALUES ". implode(",", $permsql) .";");
}
?>